package org.jim.server.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jim.core.ImChannelContext;
import org.jim.core.ImConst;
import org.jim.core.ImSessionContext;
import org.jim.core.packets.im.chat.command.ChatReqCmd;
import org.jim.core.packets.pub.pojo.JimUser;
import org.jim.core.session.id.impl.UUIDSessionIdGenerator;
import org.jim.core.utils.JsonKit;

/**
 * @FileName:
 * @Description:
 * @Author linjie
 * @Date 2020/8/245:38 PM
 * @Version 4.0.0
 */
@Slf4j
public class ImChatKit extends ChatKit {
    /**
     * 转换为聊天消息结构;
     *
     * @param body
     * @param imChannelContext
     * @return
     */
    public static ChatReqCmd toChatBody(byte[] body, ImChannelContext imChannelContext) {
        ChatReqCmd chatReqBody = parseChatBody(body);
        if (chatReqBody != null) {
            if (StringUtils.isEmpty(chatReqBody.getFrom())) {
                ImSessionContext imSessionContext = imChannelContext.getSessionContext();
                JimUser user = imSessionContext.getImClientNode().getUser();
                if (user != null) {
                    chatReqBody.setFrom(user.getNick());
                } else {
                    chatReqBody.setFrom(imChannelContext.getId());
                }
            }
        }
        return chatReqBody;
    }

    /**
     * 判断是否属于指定格式聊天消息;
     *
     * @param body
     * @return
     */
    private static ChatReqCmd parseChatBody(byte[] body) {
        if (body == null) {
            return null;
        }
        ChatReqCmd chatReqBody = null;
        try {
            String text = new String(body, ImConst.CHARSET);
            chatReqBody = JsonKit.toBean(text, ChatReqCmd.class);
            if (chatReqBody != null) {
                if (chatReqBody.getCreateTime() == null) {
                    chatReqBody.setCreateTime(System.currentTimeMillis());
                }
                if (StringUtils.isEmpty(chatReqBody.getId())) {
                    chatReqBody.setId(UUIDSessionIdGenerator.instance.sessionId(null));
                }
                return chatReqBody;
            }
        } catch (Exception e) {
            log.error(e.toString());
        }
        return chatReqBody;
    }

    /**
     * 判断是否属于指定格式聊天消息;
     *
     * @param bodyStr
     * @return
     */
    public static ChatReqCmd parseChatBody(String bodyStr) {
        if (bodyStr == null) {
            return null;
        }
        try {
            return parseChatBody(bodyStr.getBytes(ImConst.CHARSET));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }


    /**
     * 获取双方会话ID
     *
     * @param from
     * @param to
     * @return
     */
    public static String sessionId(String from, String to) {
        if (from.compareTo(to) <= 0) {
            return from + "-" + to;
        } else {
            return to + "-" + from;
        }
    }
}
